package com.xianyun.site.support.executor.filter.support;

import com.xianyun.common.core.filter.Filter;
import com.xianyun.common.core.filter.FilterInvoker;
import com.xianyun.common.redis.service.RedisService;
import com.xianyun.site.support.common.exception.SupportErrorCode;
import com.xianyun.site.support.common.exception.SupportException;
import com.xianyun.site.support.domain.model.ReceiveMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author mac_zyj
 */
@Slf4j
@Component
public class BlockFilter implements Filter<ReceiveMessage> {

    @Autowired
    private RedisService redisService;

    @Override
    public void doFilter(ReceiveMessage context, FilterInvoker nextFilter) {
        String checkKey = context.getRedisCheckKey("_CHECK");
        boolean flag = false;
        //如果没有成功 进行自旋 知道设置成功为止
        while(!flag){
            //当前的值
            Object result=redisService.getCacheObject(checkKey);
            flag = compareAndCheck(result,context,checkKey);
        }
        nextFilter.invoke(context);
    }

    private boolean compareAndCheck(Object result,ReceiveMessage context,String checkKey){
        boolean isOk = true;
        if(null != result){
            if (!context.getTransactionId().equals(result.toString())){
                if (null != redisService.getCacheObject(checkKey)){
                    if (redisService.getCacheObject(checkKey).toString().equals(result.toString())){
                        log.info("消息拥塞----并发拦截---"+checkKey+"---弃用---事务编号----"+context.getTransactionId());
                        throw new SupportException(SupportErrorCode.SYS_MQ_BLOCK,"消息并发拥塞");
                    }else {
                        isOk=false;
                    }
                }
            }
        }
        return isOk;
    }
}
